/*
 * Copyright 2008-2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ScheduledJob.java | Created on Sep 1, 2010
 */
package org.gp.scheduler.job;

import org.gp.scheduler.ScheduledJobException;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * The abstract class for scheduled jobs
 *
 * @author Paul Augustine C. Mendoza
 */
public abstract class AbstractBackgroundJob implements StatefulJob, BackgroundJob {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Map<String, String> params;

    public AbstractBackgroundJob() {
        this.params = new HashMap<String, String>();
    }

    protected abstract boolean refireImmediately();

    public void execute(JobExecutionContext jobExecutionContext) throws
            JobExecutionException {
        JobDataMap data = jobExecutionContext.getJobDetail().getJobDataMap();
        this.params = data.getWrappedMap();
        try {
            runJob();
        } catch (ScheduledJobException e) {
            handleException(e);
        }
    }

    private void handleException(Exception e) {
        JobExecutionException jee = new JobExecutionException(e);
        if (refireImmediately()) {
            jee.refireImmediately();
        } else {
            jee.setUnscheduleAllTriggers(true);
        }
        logger.error(e.getMessage(), e);
    }

    protected Map<String, String> getParameterMap() {
        return this.params;
    }

    protected Logger getLogger() {
        return this.logger;
    }

}
